package mr.ali.webvideo.controller;

import lombok.extern.slf4j.Slf4j;
import mr.ali.webvideo.Exception.R;
import mr.ali.webvideo.model.AuthRequestDTO;
import mr.ali.webvideo.model.OpenId;
import mr.ali.webvideo.service.impl.OpenIdServiceImpl;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat")
@Slf4j
public class WeChatAuthController {
    private final String userImg = "https://ikran-1329659431.cos.ap-guangzhou.myqcloud.com/icon/logo.jpg";
    private Integer userId = 111250;
    @Resource
    private OpenIdServiceImpl openIdService;

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String appSecret;

    @PostMapping("/auth")
    public R<OpenId> getOpenId(@RequestBody AuthRequestDTO requestDTO) {
        String code = requestDTO.getCode();
        Integer shareUserId = requestDTO.getShareUserId();
        try {
            log.info("code: {}", code);
            // 调用微信API获取openid
            String openIds = fetchOpenIdFromWeChat(code);
            OpenId user = openIdService.getOpenId(openIds);
            if (user == null) {
                if (shareUserId != null && shareUserId != 0) {
                    openIdService.updateNotMoney(shareUserId, 0.3, true, "");
                }
                userId++;
                OpenId openId = new OpenId().setOpenId(openIds)
                        .setGmtCreate(System.currentTimeMillis())
                        .setStatus(1)
                        .setYesMoney(0.0)
                        .setNotMoney(0.0)
                        .setStatusCreate(System.currentTimeMillis() + 259200000)
                        .setUsername("ArTv" + userId)
                        .setUserImg(userImg);
                openIdService.InsertOpenId(openId);
                return R.ok(openId);
            }
            return R.ok(user);

        } catch (Exception e) {
            return R.failed(e);
        }
    }

    private String fetchOpenIdFromWeChat(String code) throws Exception {
        log.info("appId: {}, appSecret: {}, code: {}", appId, appSecret, code);
        String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appId, appSecret, code
        );
        log.info("url: {}", url);

        // 使用HttpClient发送GET请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            String responseBody = EntityUtils.toString(response.getEntity());
            log.info("responseBody: {}", responseBody);
            JSONObject jsonObject = new JSONObject(responseBody);
            if (jsonObject.has("openid")) {
                return jsonObject.getString("openid");
            } else {
                throw new RuntimeException("Failed to get openid: " + responseBody);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    }
}
